<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Station;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class HomeStationController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Station $station;


    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**检查充电站是否存在
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function checkStation(RequestInterface $request):ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $address = $request->inputs(['province_id','city_id','area_id','name']);
        $station = $this->station
            ->where('province_id',$address['province_id'])
            ->where('city_id',$address['city_id'])
            ->where('area_id',$address['area_id'])
            ->where('name',$address['name'])
            ->where('distributor_id',$info['id'])
            ->first();
        if($station){
            return $this->success($station);
        }
        return $this->error('1002','暂无该站点');
    }

    /**解绑设备
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function unbindDevice(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $sn = $request->input('sn');
        $sn = trim($sn);
        if(!$sn){
            return $this->error(code:1002,msg:'设备编号不能为空');
        }
        $device = $this->device->where('sn',$sn)->first();
        $device->station_id = 0;
        $device->save();
        return $this->success();
    }


    /**添加设备
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function bindDevice(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['sn','address','name','images',
            'lat','lng','province_name','city_name','area_name','province_id',
            'city_id','area_id']);
        if(!$params['name']){
            return $this->error(code:1002,msg:'电站名称不能为空');
        }
        if(!$params['area_id']){
            return $this->error(code:1002,msg:'请至少定位到包含区/县信息');
        }
        if(!$params['lat'] || !$params['lng']){
            return $this->error(code:1002,msg:'经纬度不能为空');
        }
        if(!$params['sn']){
            return $this->error(code:1002,msg:'设备编号不能为空');
        }
        $station =  $this->station
            ->where('area_id',$params['area_id'])
            ->where('name',$params['name'])
            ->where('distributor_id',$info['id'])
            ->first();
        $params['sn'] = trim($params['sn']);
        $device = $this->device->where('sn',$params['sn'])->first();
        if(!$station){
            $saveStation['distributor_id'] = $info['id'];
            $saveStation['name'] = $params['name'];
            $saveStation['lat'] = $params['lat'];
            $saveStation['lng'] = $params['lng'];
            $saveStation['address'] = $params['address'];
            $saveStation['province_name'] = $params['province_name'];
            $saveStation['province_id'] = $params['province_id'];
            $saveStation['city_id'] = $params['city_id'];
            $saveStation['city_name'] = $params['city_name'];
            $saveStation['area_id'] = $params['area_id'];
            $saveStation['area_name'] = $params['area_name'];
            if($params['images']){
                $saveStation['images'] = json_encode($params['images']);
            }
            $station = Station::create($saveStation);
        }else{
            if($params['images']) {
                $station->images = json_encode($params['images']);
            }
            $station->lng = $params['lng'];
            $station->lat = $params['lat'];
            $station->save();
        }
        Device::addStation($device->id.'',(float)$params['lng'],(float)$params['lat']);
        if(!$device){
            return $this->error('1002','该设备编号不存在');
        }
        if($device->station_id > 0){
            return $this->error('1002','该设备已绑定站点 请先解绑');
        }
        if(!$device){
            return $this->error('1002','设备编号不存在');
        }
        if($info['level'] == Distributors::LEVEL_1){
            if($device->distributor_id > 0 && $device->distributor_id != $info['id']){
                return $this->error(1002,'该设备已绑定其他一级分销商');
            }
            $device->distributor_id = $info['id'];
            $device->child_distributor_id = 0;
        }else{
            $distributor = $this->distributors->where('id',$info['id'])->first();
            if($distributor->parent_id <= 0){
                if($device->distributor_id > 0){
                    $distributor->parent_id = $device->distributor_id;
                    $distributor->save();
                }
            }
            if($device->distributor_id > 0 && $distributor->parent_id > 0 &&  $distributor->parent_id != $device->distributor_id  ){
                return $this->error(1002,'设备归属异常 请联系管理员');
            }
            if($device->child_distributor_id > 0 && $device->child_distributor_id != $info['id']){
                return $this->error(1002,'该设备已绑定其他二级分销商');
            }
            $device->child_distributor_id = $info['id'];
        }
        $charge = ChargeOption::where('distributor_id',0)->orderBy('sort','desc')->first();
        $device->station_id = $station->id;
        if($charge){
            $device->charge_id = $charge->id;
        }
        $device->save();
        return $this->success();
    }

    /**电站列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function list(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $list = $this->station->where('distributor_id',$info['id'])
            ->get();
        return $this->success($list);
    }

}
